<?php

namespace App\Models\User;

use App\Helpers\SelfEncrypt;
use App\Models\BaseModel;
use App\Models\ManageAdminModel;
use App\Models\PlatFinanceModel;
use App\Models\System\CurrencyModel;
use Carbon\Carbon;
use Frontend\Models\UserBaseModel;

class AccountCorrectModel extends BaseModel
{
    protected $table = 'account_correct';

    protected $primaryKey = 'id';

    public $dateFormat = 'U';

    public function target()
    {
        return $this->belongsTo('DC\UserCenter\Models\UserBaseModel','target_uid','member_id');
    }

    public function createRecord($user_id,$money,$field,$inout = 1)
    {
        $currency = CurrencyModel::where('name',$field)->select(['id','title'])->first();
        $info = $this;
        $info->target_uid = $user_id;
        $info->flow_sn = SelfEncrypt::createCode('CA');
        $info->money = $money;
        $info->money_type = $currency->id;
        $info->inout = $inout;
        $admin = ManageAdminModel::init()->getLoginInfo();
        $info->operator_id =$admin['mgr_id'];
        if($inout==1){
            $text = '管理员'.$admin['mgr_name']."给会员%s增加".$money.$currency->title;
        }else{
            $text = '管理员'.$admin['mgr_name']."扣除会员%s".$money.$currency->title;
        }
        $info->comment =$text;


        PlatFinanceModel::init()->countRgMoney($money);

        $money_field = "money".$currency->id;
        $user = UserBaseModel::find($user_id);
        $params = [
            'money_type'=>$currency->id,
            'change_type'=>41,
            'before_money'=>$user->wallet[$money_field],
        ];
        AccountFlowModel::init()->createFlow($user_id,$money,$inout,$params);

        return $info->save();
    }
}
